import { useEffect, useRef, useState } from "react";
import {
  Button,
  Card,
  Drawer,
  Form,
  Input,
  Space,
  Select,
  Spin,
  Tabs,
  Col,
  Row,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import teamService, { type PageListReq } from "@/api/services/mes/teamService";
import type { MesTeam } from "./entity";
import { toast } from "sonner";
import { t } from "@/locales/i18n";
import useDictionary from "@/hooks/system/useDictionary";
import TableDictTag from "@/components/grid/TableDictTag";
import MesTeamMemberPage, { type MesTeamMemberHandles } from "./member";
import CustomTable from "@/components/grid/CustomTable";
import { UserAddOutlined } from "@ant-design/icons";
import SingleUserSelector from "@/pages/components/selector/SingleUserSelect";
const { TextArea } = Input;

export default function MesTeamPage() {
  const TeamMemberRef = useRef<MesTeamMemberHandles>(null);

  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    teamCode: undefined,
    teamName: undefined,
    teamType: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<MesTeam[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editingData, setEditingData] = useState<MesTeam | null>(null);
  const [form] = Form.useForm();
  const [isView, setIsView] = useState(true);

  const [userSelectVisiable, setUserSelectVisiable] = useState(false);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const teamTypeOptions = useDictionary("mes_team_type");

  const columns: ColumnsType<MesTeam> = [
    {
      title: "班组编号",
      width: 120,
      key: "teamCode",
      dataIndex: "teamCode",
    },
    {
      title: "班组名称",
      width: 120,
      key: "teamName",
      dataIndex: "teamName",
    },
    {
      title: "班长",
      width: 120,
      key: "masterName",
      dataIndex: "masterName",
    },
    {
      title: "班组类型",
      width: 120,
      key: "teamType",
      dataIndex: "teamType",
      render: (_, record) => (
        <TableDictTag dictCode="mes_team_type" value={record.teamType ?? ""} />
      ),
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      fixed: "right",
      key: "operation",
      align: "center",
      width: 100,
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => handleView(record)}>
            {t("common.view")}
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            {t("common.edit")}
          </Button>
        </Space>
      ),
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    teamService
      .pageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  //触发编辑按钮
  const handleEdit = (mesTeam: MesTeam) => {
    setEditingData(mesTeam);
    form.setFieldsValue(mesTeam);
    setDrawerVisible(true);
    setIsView(false);
  };

  //触发视图按钮
  const handleView = (mesTeam: MesTeam) => {
    setEditingData(mesTeam);
    form.setFieldsValue(mesTeam);
    setIsView(true);
    setDrawerVisible(true);
  };

  //提交表单数据
  const handleSubmit = async (values: MesTeam) => {
    try {
      setSubmitLoading(true);

      //班组成员
      const deleteTeamMemberIds = TeamMemberRef.current?.getDeleteIds();
      const addTeamMembers = TeamMemberRef.current?.getAddList();
      const updateTeamMembers = TeamMemberRef.current?.getUpdateList();

      const data = {
        ...values,
        id: editingData?.id,
        deleteTeamMemberIds: deleteTeamMemberIds,
        addTeamMembers: addTeamMembers,
        updateTeamMembers: updateTeamMembers,
      };
      if (editingData) {
        await teamService.update(data);
        toast.success("更新班组成功");
      } else {
        await teamService.add(data);
        toast.success("创建班组成功");
      }
      setDrawerVisible(false);
      setEditingData(null);
      form.resetFields();
      fetchPageList();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingData(null);
    form.resetFields();
  };

  const handleAdd = () => {
    setEditingData(null);
    form.resetFields();
    setDrawerVisible(true);
    setIsView(false);
  };

  const handleDelete = async () => {
    try {
      setLoading(true);
      await teamService.remove(selectedRowKeys);
      toast.success("删除班组成功");
      setSelectedRowKeys([]);
      fetchPageList();
    } catch (error) {
      toast.error(`删除失败: ${error.message}`);
    } finally {
      setLoading(false);
    }
  };

    const showUserSelect = () => {
      setUserSelectVisiable(true);
    };
    const handleSelectUser = (user?: UserInfo) => {
      form.setFieldsValue({
        masterId: user?.id,
        masterName: user?.name,
      });
      setUserSelectVisiable(false);
    };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="teamCode" label="班组编号">
            <Input placeholder="请输入班组编号" allowClear />
          </Form.Item>
          <Form.Item name="teamName" label="班组名称">
            <Input placeholder="请输入班组名称" allowClear />
          </Form.Item>
          <Form.Item name="teamType" label="班组类型">
            <Select options={teamTypeOptions} allowClear style={{width: 170}}/>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          total={total}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onRefresh={fetchPageList}
          onPageChange={handlePageChange}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
      <Drawer
        title={editingData ? "编辑班组" : "新增班组"}
        width={800}
        open={drawerVisible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            {!isView && (
              <Button type="primary" onClick={() => form.submit()}>
                确定
              </Button>
            )}
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="teamCode"
                label="班组编号"
                rules={[
                  {
                    required: true,
                    message: "请填写班组编号",
                  },
                ]}
              >
                <Input placeholder="请输入班组编号" allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="teamName"
                label="班组名称"
                rules={[
                  {
                    required: true,
                    message: "请填写班组名称",
                  },
                ]}
              >
                <Input placeholder="请输入班组名称" allowClear />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item name="masterId" label="班长" hidden>
								<Input />
							</Form.Item>
              <Form.Item name="masterName" label="班长">
                <Input.Search
									placeholder="请选择班长"
									allowClear
									enterButton={<UserAddOutlined />}
									onSearch={showUserSelect}
								/>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="teamType"
                label="班组类型"
                rules={[
                  {
                    required: true,
                    message: "请填写班组类型",
                  },
                ]}
              >
                <Select options={teamTypeOptions} allowClear />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={24}>
              <Form.Item name="remark" label="备注" labelCol={{ span: 3 }} wrapperCol={{ span: 21 }}>
                <TextArea />
              </Form.Item>
            </Col>
          </Row>

          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1  ",
                label: "班组成员",
                children: (
                  <MesTeamMemberPage
                    ref={TeamMemberRef}
                    parentId={editingData?.id}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>

			{/* 班长选择器 */}
			<SingleUserSelector
				open={userSelectVisiable}
				onCancel={() => setUserSelectVisiable(false)}
				onOk={(selectUser) => handleSelectUser(selectUser)}
			/>

    </Spin>
  );
}
